Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Collation Rules for Deletion and Aggregation

Spread the love

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Collation and findOneAndDelete

We can set collation rules with the findOneAndDelete method.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const db = client.db("test");
    await db.dropCollection('test');
    await db.createCollection("test");
    const testCollection = await db.collection('test');
    await testCollection.createIndex(
      { 'name': 1 },
      { 'collation': { 'locale': 'en' } });
    await testCollection.dropIndexes();
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    testCollection
      .findOneAndDelete(
        { qty: { $gt: "5" } },
        { collation: { locale: "en", numericOrdering: true } },
      );
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call findOneAndDelete with an object with the collation property to set the locale for the collation rule.

Collation and Aggregation

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const db = client.db("test");
    await db.dropCollection('test');
    await db.createCollection("test");
    const testCollection = await db.collection('test');
    await testCollection.createIndex(
      { 'name': 1 },
      { 'collation': { 'locale': 'en' } });
    await testCollection.dropIndexes();
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "apples", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    const cursor = await testCollection
      .aggregate(
        [
          { $group: { "_id": "$name", "nameCount": { "$sum": 1 } } },
          { $sort: { "_id": 1 } },
        ],
        { collation: { locale: "en", numericOrdering: true } },
      );
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call aggregate on testCollection with an array of aggregation rules that we want to apply.

We aggregate the names together and get the count of each name.

Then we sort by the _id value which is the value of the name field.

We then sort by the _id in ascending order.

In the 2nd argument, we set the collation rule.

Then the result we get from the cursor is:

{ _id: 'apples', nameCount: 2 }
{ _id: 'avocados', nameCount: 1 }
{ _id: 'oranges', nameCount: 1 }

Conclusion

We can use collation rules with the findOneAndDelete and aggregate methods of a MongoDB collection object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *